package com.zhongli.devplatform.security.qq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.bean.SecurityUser;
import com.zhongli.devplatform.mapper.sys.ReadRoleMapper;
import com.zhongli.devplatform.mapper.user.ReadUserInfoMapper;
import com.zhongli.devplatform.mapper.user.ReadUserMapper;
import com.zhongli.devplatform.po.user.ReadRolePO;
import com.zhongli.devplatform.po.user.ReadUserInfoPO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.utils.StringUtils;
import com.zhongli.devplatform.component.qq.QQAuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义qq管理授权类
 * @author WuXiCheng
 */
@Slf4j
public class QQAuthenticationManager implements AuthenticationManager {

    private static final List<GrantedAuthority> AUTHORITIES = new ArrayList<>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    @Autowired
    private ReadUserMapper userMapper;
    @Autowired
    private ReadRoleMapper roleMapper;
    @Autowired
    private ReadUserInfoMapper userInfoMapper;
    @Autowired
    private QQAuthUtil qqAuthUtil;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        QQAuthenticationToken qqAuthenticationToken = (QQAuthenticationToken) authentication;
        String openId = qqAuthenticationToken.getQqId();
        //查询数据库是否存在该qq用户
        ReadUserPO userPO = userMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("qq_id", openId));
        //如果数据库没有就直接返回qq用户的信息
        if (userPO == null) {
            QQUserInfo qqUserInfo = null;
            if (authentication.getName() != null && authentication.getCredentials() != null){
                qqUserInfo = qqAuthUtil.getUserInfo(authentication.getName(), (String) authentication.getCredentials());
            }
            assert qqUserInfo != null;
            log.info("qq用户信息为{}：",qqUserInfo.toString());
            return new UsernamePasswordAuthenticationToken(qqUserInfo,null,AUTHORITIES);
        }
        ReadUserInfoPO readUserInfoPO = userInfoMapper.selectOne(new QueryWrapper<ReadUserInfoPO>().eq("user_id",userPO.getId()));
        //获取用户所拥有的角色
        List<ReadRolePO> readRolePOS = roleMapper.selectList(new QueryWrapper<ReadRolePO>().inSql("id",
                "select role_id from read_user_role where user_id =" + userPO.getId()));
        //开始授权
        String roles = StringUtils.join(readRolePOS);
        List<SimpleGrantedAuthority> authorities = getAuthorities(roles);
        //设置当前用户所需信息
        SecurityUser customUser = new SecurityUser(userPO.getAccountNum(), userPO.getPassword(), authorities);
        customUser.setId(userPO.getId());
        customUser.setInfoId(readUserInfoPO.getId());
        log.info("QQ用户{}验证通过",userPO.getAccountNum());
        return new QQAuthenticationToken(openId,customUser);
    }

    private List<SimpleGrantedAuthority> getAuthorities(String roles) {
        String[] authorities = roles.split(",");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (String role : authorities) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        return simpleGrantedAuthorities;
    }

}